//
//  IPAddress.m
//  game
//
//  Created by yun on 2018/3/21.
//  Copyright © 2018年 YD. All rights reserved.
//

#import "IPAddress.h"

NSString *const y_ipAddress = @"y_ipAddress";
// 默认ip地址
static NSString *const defaultIPAddress = @"127.0.0.1";

@implementation IPAddress

+ (void)getIPAddressOfExternalNetwork{
    
    NSURL *url = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    NSURLSessionDataTask *sessionDataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            [[NSUserDefaults standardUserDefaults] setObject:defaultIPAddress forKey:y_ipAddress];
        } else {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            // 安全操作
            if (dict[@"data"] && dict[@"data"][@"ip"]) {
                [[NSUserDefaults standardUserDefaults] setObject:dict[@"data"][@"ip"] forKey:y_ipAddress];
            } else {
                [[NSUserDefaults standardUserDefaults] setObject:defaultIPAddress forKey:y_ipAddress];
            }

        }
        [[NSUserDefaults standardUserDefaults] synchronize];
    }];
    [sessionDataTask resume];
    
}

@end
